<template>
  <el-dialog title="修改登录密码" :visible.sync="resetPasswdShow" width="400px"
             @close="$emit('update:resetPwdShow', false)" :before-close="handlerClose">
    <el-dialog
      width="300px"
      :title="resetResultShow.result === true ? '成功' : '失败'"
      :visible.sync="resetShow"
      append-to-body
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false">
      <span>{{resetResultShow.message}}</span>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeResultShow">确认</el-button>
      </div>
    </el-dialog>
    <el-form :model="resetPwd" :rules="rules" ref="resetPwd" label-width="120px">
      <el-form-item label="用户名:" prop="telphone" required>
        <el-input v-model.trim="resetPwd.telphone" disabled></el-input>
      </el-form-item>
      <el-form-item label="短信验证码：" required class="smsCode">
        <el-input v-model="resetPwd.smsCode">
          <template slot="append">
            <el-button type="text" @click="getPhoneWord" v-if="!isHasValidCode" :loading="isGetInterface">
              发送验证码
            </el-button>
            <span class="" v-else>{{tipMessage}}</span>
          </template>
        </el-input>
      </el-form-item>
      <!--<el-form-item label="旧密码:" prop="oldPassword" required>-->
      <!--<el-input v-model.trim="accountInfo.oldPassword" type="password"></el-input>-->
      <!--</el-form-item>-->
      <el-form-item label="新密码:" prop="firstPassword" required>
        <el-input v-model.trim="resetPwd.firstPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码:" prop="secondPassword" required>
        <el-input v-model.trim="resetPwd.secondPassword" type="password"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm('resetPwd')">确认</el-button>
      <el-button @click="closeModel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import md5 from 'js-md5'
  export default {
    name: "ResetPassword",
    props: {
      resetPwdShow: {
        type: Boolean,
        default: false
      }
    },
    data() {
      var validateEnsurePwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.resetPwd.firstPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
      return {
        resetPasswdShow:this.resetPwdShow,
        resetShow: false,
        tipMessage: "",
        isHasValidCode: false,
        isGetInterface: false,
        resetPwd: {
          // password: "",
          // newPassword: "",t
          // confirmPassword: ""
          smsCode: "",
          telphone: JSON.parse(window.localStorage.adminLogin).telphone,
          firstPassword: "",
          secondPassword: ""
        },
        resetResultShow:{
          result:true,
          message:"密码修改成功，返回登录页"
        },
        rules: {
          smsCode: [
            {required: true, message: '验证码不能为空', trigger: ['blur', 'change']}
          ],
          firstPassword: [
            {
              validator: window.validate.invalidSymbol, trigger: ['blur', 'change']
            },
            {
              required: true, message: '新密码不能为空', trigger: ['blur', 'change'],

            },
            { min: 6, max: 12, message: '密码长度为6-12位', trigger: ['blur', 'change'] },
          ],
          secondPassword: [
            {
              validator: window.validate.invalidSymbol, trigger: ['blur', 'change']
            },
            {
              required: true, message: '确认密码不能为空', trigger: ['blur', 'change']
            },
            { min: 6, max: 12, message: '密码长度为6-12位', trigger: ['blur', 'change'] },
          ]
        }
      }
    },
    watch: {
      resetPwdShow () {
        this.resetPasswdShow = this.resetPwdShow;
      }
    },
    methods: {
      getPhoneWord() {
        this.isGetInterface = true;
        this.isHasValidCode = true;
        let data = {
          codeType: 11,
          roleType: JSON.parse(window.localStorage.adminLogin).userType,
          telphone: this.resetPwd.telphone
        };
        let time = 60;
        this.tipMessage = time + "秒";
        setInterval(() => {
          if(time <= 0) {
            this.tipMessage = "发送验证码"
            this.isGetInterface = false;
            this.isHasValidCode = false;
            return ;
          }
          time --;
          this.tipMessage = time + "秒";
        }, 1000)
        ajax.post(apis.common.sendCode, data).then(res => {
          if(res.code === "10000000") {

          } else {
            this.$message.error(res.message)
          }
          this.isGetInterface = false;
        });
      },
      handlerClose(done) {
        this.resetForm();
        done()
      },
      closeModel() {
        this.resetForm();
        this.resetPasswdShow = false
      },
      // 重置
      resetForm() {
        this.$refs['resetPwd'].resetFields()
      },
      submitForm(formName) {
        let data = {
          ...this.resetPwd,
          firstPassword: md5(this.resetPwd.firstPassword).toUpperCase(),
          secondPassword: md5(this.resetPwd.secondPassword).toUpperCase(),
          userLogo: JSON.parse(window.localStorage.adminLogin).userLogo
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // this.resetPassword(this.resetPwd)
            ajax.post(apis.home.changeAccountInfo, data).then(res => {
              if(res.code === "10000000") {
                this.$message({
                  type: 'success',
                  message: '密码修改成功!'
                });
                window.localStorage.removeItem('adminLogin')
                this.$router.push({ name: 'login' })
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            return false;
          }
        });
      },
      resetPassword(data) {
        ajax.post(apis.admin.resetPassword, data).then(res => {
          if (res.code === "200") {
            this.resetShow = true
          } else {
            this.resetResultShow.result = false
            this.resetResultShow.message = res.message
            this.resetShow = true
          }
        }).catch(err => {
          console.log(err)
        })
      },
      closeResultShow(){
        if(this.resetResultShow.result){
          this.goToLogin()
        }else{
          this.$refs["resetPwd"].resetFields();
          this.resetShow = false
        }
      },
      goToLogin() {
        window.localStorage.removeItem('login')
        this.$router.push({name: 'login'})
      }
    }
  }
</script>

<style lang="scss" scoped>
  .smsCode {
    .el-input {
      .el-button {
        padding: 0 10px;
      }
    }
  }
</style>
